package com.example.kiratest.realize;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.AndroidPublisherScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class GooglePlayApiClient {
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    private static final String APPLICATION_NAME = "Google Play Developer API Client";
    private static final String SERVICE_ACCOUNT_JSON = "path/to/your/service-account.json";
    
    private final AndroidPublisher publisher;

    public GooglePlayApiClient() throws GeneralSecurityException, IOException {
        final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        this.publisher = new AndroidPublisher.Builder(
                httpTransport, 
                JSON_FACTORY, 
                getCredentials())
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    private HttpRequestInitializer getCredentials() throws IOException {
        GoogleCredentials credentials = ServiceAccountCredentials
                .fromStream(new FileInputStream(SERVICE_ACCOUNT_JSON))
                .createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER));
        
        return new HttpCredentialsAdapter(credentials);
    }

    public String getAppVersion(String packageName) throws IOException {
        try {
            AndroidPublisher.Edits edits = publisher.edits();
            AndroidPublisher.Edits.Insert editRequest = edits.insert(packageName, null);
            com.google.api.services.androidpublisher.model.AppEdit edit = editRequest.execute();
            
            String editId = edit.getId();
            AndroidPublisher.Edits.Tracks.Get getRequest = edits.tracks()
                    .get(packageName, editId, "production");
            
            com.google.api.services.androidpublisher.model.Track track = getRequest.execute();
            if (track.getReleases() != null && !track.getReleases().isEmpty()) {
                return track.getReleases().get(0).getVersionCodes().get(0).toString();
            }
            
            return null;
        } catch (Exception e) {
            System.err.println("Error getting version for " + packageName + ": " + e.getMessage());
            return null;
        }
    }

    public static void main(String[] args) {
        try {
            GooglePlayApiClient client = new GooglePlayApiClient();
            
            String[] testPackages = {
                "com.mobile.legends",
                "com.instagram.android",
                "com.whatsapp",
                "com.tencent.mm"
            };

            for (String pkg : testPackages) {
                long start = System.currentTimeMillis();
                String version = client.getAppVersion(pkg);
                long duration = System.currentTimeMillis() - start;

                System.out.printf("%-20s -> %-15s (%-4dms)%n%n",
                        pkg,
                        version != null ? version : "NOT FOUND",
                        duration);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}